/*
 * Copyright 2010 Thedwick, LLC

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */
package com.thedwick.jdbcGrabber.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

public class IOUtil {
	private IOUtil() {
		//utility class, should not be instantiated
	}
	
	/** 
	 * Just a convenience method to avoid littering code with if's and catches
	 * @param in
	 */
	public static void close(OutputStream in){
		try {
			if (in != null){
				in.close();
			}
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	/** 
	 * Just a convenience method to avoid littering code with if's and catches
	 * @param in
	 */
	public static void close(Writer in){
		try {
			if (in != null){
				in.close();
			}
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	public static void safeAppend(String content, File target) throws IOException {
		FileWriter fileWriter = new FileWriter(target, true);
		try {
			fileWriter.append(content);
			fileWriter.flush();
		} finally {
			IOUtil.close(fileWriter);
		}
	}

	public static void safeReplace(String string, File target) throws IOException {
		if (target.exists()){
			if (!target.delete()){
				throw new IOException("failed to delete file: " + target.getAbsolutePath());
			}
		}
		FileWriter fileWriter = new FileWriter(target);
		try {
			fileWriter.append(string);
			fileWriter.flush();
		} finally {
			IOUtil.close(fileWriter);
		}
	}
}
